package com.zjgeport.zjgdanger.Analysis;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.zjgeport.zjgdanger.Charts.charts.HorizontalBarChart;
import com.zjgeport.zjgdanger.Charts.components.AxisBase;
import com.zjgeport.zjgdanger.Charts.components.Legend;
import com.zjgeport.zjgdanger.Charts.components.XAxis;
import com.zjgeport.zjgdanger.Charts.components.YAxis;
import com.zjgeport.zjgdanger.Charts.data.BarData;
import com.zjgeport.zjgdanger.Charts.data.BarDataSet;
import com.zjgeport.zjgdanger.Charts.data.BarEntry;
import com.zjgeport.zjgdanger.Charts.data.Entry;
import com.zjgeport.zjgdanger.Charts.formatter.IAxisValueFormatter;
import com.zjgeport.zjgdanger.Charts.highlight.Highlight;
import com.zjgeport.zjgdanger.Charts.interfaces.datasets.IBarDataSet;
import com.zjgeport.zjgdanger.Charts.listener.OnChartValueSelectedListener;
import com.zjgeport.zjgdanger.Charts.utils.ColorTemplate;
import com.zjgeport.zjgdanger.Charts.utils.MPPointF;
import com.zjgeport.zjgdanger.CommonActivity;
import com.zjgeport.zjgdanger.LoginActivity;
import com.zjgeport.zjgdanger.R;
import com.zjgeport.zjgdanger.common.DangerAxisValueFormatter;
import com.zjgeport.zjgdanger.common.LogUtils;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.myApplication;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class DangerTypeTJActivity extends CommonActivity implements OnChartValueSelectedListener {

    protected HorizontalBarChart mChart;

    private List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_danger_type_tj);
        findTextViewById(R.id.title).setText("按危险类别统计");
        initCommonListener();
        initData();
    }

    private void initView()
    {
        mChart = (HorizontalBarChart)findViewById(R.id.chart);
        mChart.setOnChartValueSelectedListener(this);
        // mChart.setHighlightEnabled(false);

        mChart.setDrawBarShadow(false);

        mChart.setDrawValueAboveBar(true);

        mChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        // draw shadows for each bar that show the maximum value
        // mChart.setDrawBarShadow(true);

        mChart.setDrawGridBackground(false);

        XAxis xl = mChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTH_SIDED.BOTTOM);
        xl.setTypeface(mTfLight);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(false);
        xl.setGranularity(10f);
        xl.setValueFormatter(new DangerAxisValueFormatter(data));


        YAxis yl = mChart.getAxisLeft();
        yl.setTypeface(mTfLight);
        yl.setDrawAxisLine(true);
        yl.setDrawGridLines(true);
        yl.setSpaceBottom(0f);
//        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
////        yl.setInverted(true);

        YAxis yr = mChart.getAxisRight();
        yr.setTypeface(mTfLight);
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setSpaceBottom(0f);
//        yr.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        yr.setInverted(true);

        setData(data.size(), 50);
        mChart.setFitBars(true);
        mChart.animateY(2500);

        com.zjgeport.zjgdanger.Charts.components.Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(com.zjgeport.zjgdanger.Charts.components.Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setFormSize(8f);
        l.setEnabled(false);
        l.setXEntrySpace(4f);

    }

    /**
     * 初始化数据列表信息
     */
    private void initData() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("getriskMap");
        method.setKvdata(map);
        HttpClient.postdata(new Button(DangerTypeTJActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        data.addAll(data1);
                    }

                } else {
                    Toast.makeText(getApplication(),result.getResultMessage(),1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(DangerTypeTJActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }

                // 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = WHAT_DID_LOAD_DATA;
                msg.obj = data;
                handler.sendMessage(msg);

            }
        });
    }

    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:
                    initView();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                List<IBarDataSet> sets = mChart.getData()
                        .getDataSets();

                for (IBarDataSet iSet : sets) {

                    IBarDataSet set = (BarDataSet) iSet;
                    set.setDrawValues(!set.isDrawValuesEnabled());
                }

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleIcons: {
                List<IBarDataSet> sets = mChart.getData()
                        .getDataSets();

                for (IBarDataSet iSet : sets) {

                    IBarDataSet set = (BarDataSet) iSet;
                    set.setDrawIcons(!set.isDrawIconsEnabled());
                }

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if(mChart.getData() != null) {
                    mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
                    mChart.invalidate();
                }
                break;
            }
            case R.id.actionTogglePinch: {
                if (mChart.isPinchZoomEnabled())
                    mChart.setPinchZoom(false);
                else
                    mChart.setPinchZoom(true);

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
                mChart.notifyDataSetChanged();
                break;
            }
            case R.id.actionToggleBarBorders: {
                for (IBarDataSet set : mChart.getData().getDataSets())
                    ((BarDataSet)set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);

                mChart.invalidate();
                break;
            }
            case R.id.animateX: {
                mChart.animateX(3000);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(3000);
                break;
            }
            case R.id.animateXY: {

                mChart.animateXY(3000, 3000);
                break;
            }
            case R.id.actionSave: {
                if (mChart.saveToGallery("title" + System.currentTimeMillis(), 50)) {
                    Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",
                            Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
                            .show();
                break;
            }
        }
        return true;
    }

    private void setData(int count, float range) {

        float barWidth = 7f;
        float spaceForBar = 10f;
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < count; i++) {
            HashMap<String, String> dataMap = data.get(i);
            yVals1.add(new BarEntry(i * spaceForBar, Float.parseFloat(dataMap.get("SCOUNT").toString()), getResources().getDrawable(R.drawable.star)));
        }

        BarDataSet set1;

        List<Integer> colors = new ArrayList<>();
        colors.add(Color.parseColor("#9cc969"));
        colors.add(Color.parseColor("#fc8468"));
        colors.add(Color.parseColor("#2b727a"));
        colors.add(Color.parseColor("#e67c32"));
        colors.add(Color.parseColor("#fbcd33"));
        colors.add(Color.parseColor("#b5c241"));
        colors.add(Color.parseColor("#bf2630"));


        if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet)mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            set1.setColors(colors);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "");
            set1.setColors(colors);

            set1.setDrawIcons(false);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(mTfLight);
            data.setBarWidth(barWidth);
            mChart.setData(data);
        }
    }

    protected RectF mOnValueSelectedRectF = new RectF();
    @SuppressLint("NewApi")
    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;

        RectF bounds = mOnValueSelectedRectF;
        mChart.getBarBounds((BarEntry) e, bounds);

        MPPointF position = mChart.getPosition(e, mChart.getData().getDataSetByIndex(h.getDataSetIndex())
                .getAxisDependency());

        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() {
    };


}
